<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #fieldCond>
        <a-button
          :type="dataRef.linkFieldCond && dataRef.linkFieldCond.length ? 'primary' : 'default'"
          @click="handleConfiguration"
        >
          配置条件
        </a-button>
      </template>
      <template #linkEvent="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px items-center">
            <Select
              :options="tagTypeOptions"
              v-model:value="model[field]"
              placeholder="请选择"
              style="width: 120px"
              showSearch
              optionFilterProp="label"
            />

            <Select
              v-if="model[field] == 'module'"
              style="flex: 1"
              :options="moduleList"
              v-model:value="dataRef['moduleCode']"
              placeholder="请选择"
              showSearch
              optionFilterProp="name"
              :field-names="{ label: 'name', value: 'code' }"
            />
            <template v-else-if="model[field] == 'flow'">
              <TreeSelect
                class="w-50"
                :tree-data="treeData"
                :field-names="{ label: 'name', value: 'code', key: 'code' }"
                :show-search="true"
                treeNodeFilterProp="name"
                v-model:value="dataRef['flowTypeCode']"
              />
              <a-button
                style="margin: 10px 0"
                :type="dataRef.params ? 'primary' : 'default'"
                @click="handleParams"
              >
                映射字段
              </a-button>
            </template>
            <Input
              v-model:value="dataRef['linkHref']"
              placeholder="请输入"
              title="注：点击事件方法中如有双引号将会被自动替换为单引号"
              style="flex: 1"
              v-else
            />
          </div>
        </FormItemRest>
      </template>
      <template #role>
        <SelectRoleInput
          :roleCodes="dataRef.roleCodes"
          v-model:value="dataRef.roleDescs"
          @change="(val, node) => handleRoleNames(val, node)"
        />
      </template>
      <template #iconLinkAdd>
        <FormItemRest>
          <div class="flex gap-10px items-center">
            <Select
              v-model:value="dataRef['linkIcon']"
              placeholder="请选择"
              style="flex: 1"
              showSearch
              optionFilterProp="label"
              :filter-option="filterOption"
            >
              <SelectOption
                v-for="item in flowMacroGetFontAwesomeList"
                :value="item.value"
                :key="item.value"
              >
                <i :class="`fa ${item.label}`"></i> {{ item.label }}
              </SelectOption>
            </Select>

            <Select
              style="width: 80px"
              :options="linkColorOptions"
              v-model:value="dataRef['linkColor']"
              placeholder="请选择"
              showSearch
              optionFilterProp="label"
            />
          </div>
        </FormItemRest>
      </template>
    </BasicForm>
    <FieldMappingModal
      @register="registerFieldMappingModal"
      @success="handleSuccessFieldMappingModal"
    />
    <ConfigurationModal
      @register="registerConfigurationModal"
      @success="handleSuccessConfigurationModal"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, tagTypeOptions, linkColorOptions } from './operationColumnLink.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import {
    getStampCreate,
    getFormGetFields,
    getFormFields,
    getFormGetNestFieldsWithFormName,
    getFlowGetDirTreeAll,
    getFlowMacroGetFontAwesome,
  } from '/@/api/flowManage/flowManage';
  import { getFieldsWithNest } from '/@/api/module/module';
  import { Form, Select, Input, TreeSelect } from 'ant-design-vue';
  import { TreeItem } from '/@/components/Tree';
  import { SelectRoleInput } from '/@/components/CustomComp';
  import FieldMappingModal from './FieldMappingModal.vue';
  import ConfigurationModal from '../../configuration/index';
  import { getModulesAll } from '/@/api/system/system';
  import { getVisualLinkAdd, getVisualLinkModify } from '/@/api/module/module';
  import { isArray, isObject } from '/@/utils/is';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'OperationColumnLinkDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      FormItemRest: Form.ItemRest,
      Select,
      SelectOption: Select.Option,
      Input,
      SelectRoleInput,
      FieldMappingModal,
      TreeSelect,
      ConfigurationModal,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref<any>({});
      const formCode = ref('');
      const moduleCode = ref('');
      const moduleList = ref<Recordable[]>([]);
      const { createMessage } = useMessage();

      const formGetFieldsData = ref<Recordable[]>([]);
      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 110,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        formCode.value = data?.formCode ?? '';
        moduleCode.value = data?.moduleCode ?? '';
        formGetFieldsData.value = data?.formGetFieldsData;
        dataRef.value = {};
        if (unref(isUpdate)) {
          const _data = data?.record;
          dataRef.value = {
            roleDescs: _data?.roleDescs,
            roleCodes: _data?.role,
            linkOrder: _data?.order,
            linkIcon: _data?.icon,
            linkColor: _data?.color,
            linkEvent: _data?.event,
            linkFieldCond: _data?.cond && _data?.cond.indexOf('<items') != -1 ? _data?.cond : '',
            linkName: _data?.name,
            linkNewName: _data?.name,
            linkHref: _data?.link,
            params: {},
          };
          if (dataRef.value.linkEvent == 'flow') {
            const link = isObject(dataRef.value?.linkHref) ? dataRef.value.linkHref : {};
            dataRef.value.params = link.params ? JSON.parse(link.params) : {};
            dataRef.value.flowTypeCode = link.flowTypeCode;
          } else if (dataRef.value.linkEvent == 'module') {
            dataRef.value.moduleCode = isObject(dataRef.value?.linkHref)
              ? dataRef.value?.linkHref.moduleCode
              : '';
          }
          updateSchema([
            {
              field: 'linkName',
              ifShow: false,
            },
          ]);
          updateSchema([
            {
              field: 'linkNewName',
              ifShow: true,
            },
          ]);
        } else {
          dataRef.value = {
            linkIcon: '',
            linkEvent: 'link',
            linkOrder: data?.dataSourceLength ? data?.dataSourceLength + 1 : 1,
            linkColor: '',
          };
          updateSchema([
            {
              field: 'linkName',
              ifShow: true,
            },
          ]);
          updateSchema([
            {
              field: 'linkNewName',
              ifShow: false,
            },
          ]);
        }
        setFieldsValue({
          ...unref(dataRef),
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      //获取所有模块
      const getModulesAllData = async () => {
        moduleList.value = (await getModulesAll()) || [];
      };

      const flowMacroGetFontAwesomeList = ref<Recordable[]>([]);
      //获取所有图标
      const getFlowMacroGetFontAwesomeData = async () => {
        flowMacroGetFontAwesomeList.value = [];
        const data = (await getFlowMacroGetFontAwesome()) || [];
        if (isArray(data)) {
          data.forEach((item) => {
            flowMacroGetFontAwesomeList.value.push({
              value: item,
              label: item,
            });
          });
        }
      };
      const treeData = ref<TreeItem[]>([]);
      const fetch = async () => {
        const data = (await getFlowGetDirTreeAll()) || [];
        treeData.value = setChildren(data);
        getModulesAllData();
        getFlowMacroGetFontAwesomeData();
      };

      function setChildren(node) {
        node.forEach((item) => {
          item.key = item.code;
          item.value = item.code;
          item.title = item.name;
          item.disabled = item.layer == 3 ? false : true;
          if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            item.isLeaf = false;
            setChildren(item.children);
          } else {
            item.isLeaf = true;
          }
        });
        return node;
      }
      onMounted(fetch);

      const handleRoleNames = (val, node) => {
        const { dataRef: newDataRef } = node;
        dataRef.value.roleDescs = val;
        dataRef.value.roleCodes = newDataRef['codes'];
      };

      //配置条件
      const [registerConfigurationModal, { openModal: openConfiguration }] = useModal();
      //组合条件配置
      const handleConfiguration = () => {
        openConfiguration(true, {
          list: dataRef.value.linkFieldCond || [],
          formGetFieldsData: formGetFieldsData.value,
        });
      };

      const handleSuccessConfigurationModal = ({ value }) => {
        dataRef.value.linkFieldCond = value;
      };

      const [registerFieldMappingModal, { openModal }] = useModal();
      //映射字段
      const handleParams = () => {
        if (!dataRef.value.flowTypeCode) {
          createMessage.warning('请选择流程');
          return;
        }
        openModal(true, {
          formCode: formCode.value,
          flowTypeCode: dataRef.value.flowTypeCode,
          params: dataRef.value['params'],
        });
      };
      //映射回调
      const handleSuccessFieldMappingModal = ({ params }) => {
        dataRef.value['params'] = params;
      };

      async function handleSubmit() {
        try {
          const values = await validate();
          let formData = Object.assign({}, unref(dataRef), values);
          formData.code = moduleCode.value;
          formData.formCode = formCode.value;
          if (formData.linkEvent == 'flow') {
            formData.linkHref = formData.params ? JSON.stringify(formData.params) : '';
            formData.params = formData.params ? JSON.stringify(formData.params) : '';
          } else if (formData.linkEvent == 'module') {
            const linkHref = {
              moduleCode: formData.moduleCode,
            };
            formData.linkHref = JSON.stringify(linkHref);
          }
          setDrawerProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            await getVisualLinkModify(formData);
          } else {
            await getVisualLinkAdd(formData);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
      const filterOption = (input: string, option: any) => {
        return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      };
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        dataRef,
        tagTypeOptions,
        handleRoleNames,
        linkColorOptions,
        handleParams,
        registerFieldMappingModal,
        handleSuccessFieldMappingModal,
        handleConfiguration,
        treeData,
        registerConfigurationModal,
        handleSuccessConfigurationModal,
        moduleList,
        flowMacroGetFontAwesomeList,
        filterOption,
      };
    },
  });
</script>
